Skip to main content

Hash Table

The original case/problem could be found on leedcode

case 387 (classical case) JS and PHP

var firstUniqChar = function(s) {
// make a new hash table using new Map()
map = new Map()
// counting....
for (let i = 0; i < s.length; i++) {
word = s[i]; // it can be also a number
val = map.get(word);
if (map.has(word)) {
map.set(word, val + 1)
} else {
map.set(word, 1)
}
}
// find sth. which shows uns 1 2,or 3.... times, in this sample it is one time.
for (let i = 0; i < s.length; i++) {
if (map.get(s[i]) === 1) {
return i
}
}
return NaN;
};
class Solution {

/**
* @param String $s
* @return Integer
*/
function firstUniqChar($s) {
$hashmap = []; // At php, array can be used directly as a hash table
for ($i=0;$i<strlen($s);$i++){
$word = $s[$i];
if (isset($hasmap[$word])){
$hasmap[$word] +=1;
}
else {
$hasmap[$word] = 1;
}
}
for ($i=0;$i<strlen($s);$i++){
$word = $s[$i];
if ($hasmap[$word] == 1){
return $i;
}
}
return "NaN";
}
}